﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
using System.Management;

/*
 * 作者：Billy Qing(http://www.cnblogs.com/yizhuqing)
 * 日期：2009年11月20日
 * 说明：EyesBaby 单实例运行控制
 * 版本：1.0
 */
namespace EyesBaby
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。

        /// </summary>
        [STAThread]
        static void Main()
        {
            // 控制当前电脑只有一个实例在运行
            Process instance = RunningInstance();
            if (instance == null)
            {
                //没有实例在运行

                Application.Run(new WinMain());
            }
            else
            {
                //已经有一个实例在运行
                HandleRunningInstance(instance);
            }
        }
        #region  确保程序只运行一个实例

        private static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            //遍历与当前进程名称相同的进程列表  
            foreach (Process process in processes)
            {
                //MessageBox.Show(  (GetProcessUserName(process.Id) +"=="+ GetProcessUserName(current.Id)));
                //如果实例已经存在则忽略当前进程  && (GetProcessUserName(process.Id) != GetProcessUserName(current.Id)) 

                if ((process.Id != current.Id) && (GetProcessUserName(process.Id) == GetProcessUserName(current.Id)))
                {
                    //保证要打开的进程同已经存在的进程来自同一文件路径
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        //返回已经存在的进程

                        return process;
                    }
                }
            }
            return null;
        }

        private static void HandleRunningInstance(Process instance)
        {
            MessageBox.Show("眼保系统已经在运行！", "提示信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            ShowWindowAsync(instance.MainWindowHandle, 1);  //调用api函数，正常显示窗口

            SetForegroundWindow(instance.MainWindowHandle); //将窗口放置最前端
        }
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(System.IntPtr hWnd);
        #endregion

        private static string GetProcessUserName(int pID)
        {

            string text1 = null;

            SelectQuery query1 = new SelectQuery("Select * from Win32_Process WHERE processID=" + pID);
            ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(query1);

            try
            {
                foreach (ManagementObject disk in searcher1.Get())
                {
                    ManagementBaseObject inPar = null;
                    ManagementBaseObject outPar = null;

                    inPar = disk.GetMethodParameters("GetOwner");

                    outPar = disk.InvokeMethod("GetOwner", inPar, null);

                    text1 = outPar["User"].ToString();
                    break;
                }
            }
            catch
            {
                text1 = "SYSTEM";
            }

            return text1;
        }

    }


}